<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="/css/materialize.min.css" media="screen,projection"/>
    <title>Media Images</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
    <div class="section">
        <div class="row">
            <div class="col m4">
                <a class="waves-effect waves-light blue-grey lighten-2 btn" href="upload_image.html" id="btn-upload">
                  <i class="material-icons left">file_upload</i></a>
            </div>
        </div>
    </div>
    <div class="divider"></div>
    <div class="section" id="images_list">
    </div>
    <div class="modal" id="modal_confirm">
        <div class="modal-content">
            <h4>Delete Confirm</h4>
            <p id="confirm_content"></p>
        </div>
        <div class="modal-footer">
            <a href="#" class="modal-close waves-effect waves-green btn-flat">No</a>
            <a href="#" class="modal-close waves-effect waves-green btn-flat" id="confirm_link">Yes</a>
        </div>
    </div>
    <div class="modal" id="modal-dialog">
        <!--hide model -->
        <div class="modal-content" id="modal-dialog-content">
        </div>
        <div class="modal-footer">
            <a href="#" class="modal-close waves-effect waves-green btn-flat"></a>
            <a href="#" class="modal-close waves-effect waves-green btn-flat" id="modal-dialog-confirm"></a>
        </div>
    </div>
</div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="/js/materialize.min.js"></script>
<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>

    var texts = N.GetTexts();

    function outputMessage(message){
      $('#images_list').empty().append(
        $('<div>').addClass('center').append(
          $('<span>').text(message)
        )
      );
    }

    function refresh(){
      loadImages();
    }

    function loadImages(){
      var queryURL = '/media_image_search/?session=' + N.GetSessionID();
      $.getJSON(
        queryURL,
        function(result){
          if (0 != result['error_code']) {
            outputMessage(result['message']);
            return;
          }
          if (!result['data']){
            outputMessage('no media images available');
            return;
          }

          if (0 == result['data'].length){
            outputMessage('no media images available');
            return;
          }
          var container = $('<div>').addClass('row');

          result['data'].forEach((image) => {
            var content = $('<div>').addClass('card-content');
            var tags = $('<div>');
            if (image['tags']){
              image['tags'].forEach((tag) => {
                tags.append($('<div>').addClass('chip').text(tag));
              });
            }
            var imageSize = image['size'];
            var sizeString;
            if (imageSize > (1 << 30)){
              sizeString = Math.floor(imageSize*100 / (1 << 30)) / 100 + ' GiB';
            }else{
              sizeString = Math.floor(imageSize*100 / (1 << 20)) / 100 + ' MiB';
            }

            content.append(
              $('<span>').addClass('card-title').text(image['name'])
            ).append(
              $('<p>').append(
                $('<b>').text(texts.get(N.TagSize)).append(': ' + sizeString)
              )
            ).append(
              $('<p>').text('ID: ' + image['id'])
            );
            if (image.hasOwnProperty('create_time')){
              content.append(
                $('<p>').text(texts.get(N.TagCreate) + ': ' + image['create_time'])
              );
            }
            if (image.hasOwnProperty('modify_time')){
              content.append(
                $('<p>').text(texts.get(N.TagModify) + ': ' + image['modify_time'])
              );
            }
            if (image.hasOwnProperty('description')){
              content.append(
                $('<p>').text(image['description'])
              );
            }
            content.append(tags);

            var actions = $('<div>').addClass('card-action').append(
              $('<a>').addClass('blue-grey-text tooltipped').attr('href', '#').attr('data-position', 'bottom').
                attr('data-tooltip', texts.get(N.TagDelete)).attr('onclick', 'confirmDelete("' + image['name'] + '", "' + image['id'] +'")').append(
                  $('<i>').addClass('material-icons').text('delete')
                )
            ).append(
              $('<a>').addClass('blue-grey-text tooltipped').attr('href', '#').attr('data-position', 'bottom').
                attr('data-tooltip', texts.get(N.TagModify)).attr('onclick', 'confirmModifyImage("' + image['id'] +'")').append(
                  $('<i>').addClass('material-icons').text('mode_edit')
                )
            );
            container.append(
              $('<div>').addClass('col m4').append(
                $('<div>').addClass('card').append(content).append(actions)
              )
            );
          });
          $('#images_list').empty().append(container);
          M.Tooltip.init($('.tooltipped'));
        }
      );
    }

    function confirmDelete(name, id){
      $('#confirm_content').text('Are you sure to delete image ' + name);
      $('#confirm_link').attr('onclick', 'deleteImage("' + name + '","'+ id +'")');
      var instance = M.Modal.getInstance($('#modal_confirm'));
      instance.open();
    }

    function deleteImage(name, id) {
      $.ajax({
       url:'/media_images/' + id,
       type: "DELETE",
       dataType: "json",
       success: function (result) {
           if (0 != result['error_code']) {
               M.toast({html: 'delete image fail: ' + result['message'], outDuration: 1000});
               return;
           }
           M.toast({html: 'media image "' + name + '" deleted'});
           setTimeout(refresh, 1500);
           N.WriteOperateLog('delete media image ' + name + ' / ' + id);
       }
      });
    }

    function confirmModifyImage(id) {
      var queryURL = '/media_images/' + id;
      $.getJSON(
        queryURL,
        function(result){
          if (0 != result['error_code']) {
              M.toast({html: 'get image info fail: ' + result['message'], outDuration: 1000});
            return;
          }
          if (!result['data']){
            M.toast({html: 'no media info available'});
            return;
          }
          var image = result['data'];
          var imageName = image['name'];
          var imageDescription = image['description'];
          var imageTags = image['tags'];

          var content = $('#modal-dialog-content').empty();
          if (N.IsChinese()){
            content.append(
              $('<h4>').text('修改镜像信息')
            );
          }else{
            content.append(
              $('<h4>').text('Modify Image')
            );
          }
          //name
          content.append(
            $('<div>').addClass('row').append(
              $('<div>').addClass('input-field col m4 s12').append(
                $('<label>').attr('for', 'image-name').text(texts.get(N.TagName))
              ).append(
                $('<input>').attr('type','text').attr('id', 'image-name').val(imageName)
              )
            )
          );
          content.append(
            $('<div>').addClass('row').append(
              $('<div>').addClass('input-field col m8 s12').append(
                $('<label>').attr('for', 'image-description').text(texts.get(N.TagDescription))
              ).append(
                $('<textarea>').addClass('materialize-textarea').attr('id', 'image-description').val(imageDescription)
              )
            )
          );
          var tagList = $('<div>').addClass('row');
          N.GetAllImageTags().forEach((tag)=>{
            tagList.append(
              $('<div>').addClass('col m3').append(
                $('<label>').append(
                  $('<input>').attr('type', 'checkbox').attr('name', 'image-tag').val(tag[0])
                ).append(
                  $('<span>').text(tag[1])
                )
              )
            );
          });
          content.append(
            $('<div>').addClass('row').append(
              $('<div>').addClass('col m2').append(
                $('<label>').text(texts.get(N.TagTag))
              )
            )
          ).append(
            $('<div>').addClass('row').append(
              $('<div>').addClass('col m8').append(
                tagList
              )
            )
          );
          //check tags
          imageTags.forEach((tag)=>{
            $(':checkbox[name=image-tag][value=' + tag +']').prop('checked', true);
          });
          //show
          M.updateTextFields();
          $('#modal-dialog-confirm').attr('onclick', 'modifyImage("'+ id +'")');
          var instance = M.Modal.getInstance($('#modal-dialog'));
          instance.open();
        }
      );
    }

    function modifyImage(imageID){
      var imageName = $('#image-name').val();
      if (!imageName){
        M.toast({html: 'invalid image name'});
        return;
      }
      var imageDescription = $('#image-description').val();
      if (!imageDescription){
        M.toast({html: 'input image description'});
        return;
      }

      var imageTags = new Array();
      $("input[name='image-tag']:checkbox:checked").each(function(){
        imageTags.push($(this).val());
      });
      var request = new Object();
      request.name = imageName;
      request.description = imageDescription;
      request.owner = N.GetCurrentUser();
      request.group = N.GetCurrentGroup();
      request.tags = imageTags;
      $.ajax({
       url: '/media_images/' + imageID ,
       type: "PUT",
       dataType: "json",
       data:JSON.stringify(request),
       success: function (result) {
           if (0 != result['error_code']) {
               M.toast({html: 'modify image fail: ' + result['message'], outDuration: 1000});
               return;
           }
           M.toast({html: 'image "' + imageID + '" modified'});
           setTimeout(refresh, 500);
           N.WriteOperateLog('modify media image ' + imageName + ' / ' + imageID);
       }
      });

    }

    $(function(){
      N.ValidateSession();
      $('#btn-upload').append(texts.get(N.TagUpload));
      $('.modal-footer > a:first-child').text(texts.get(N.TagCancel));
      $('.modal-footer > a:last-child').text(texts.get(N.TagConfirm));
      M.AutoInit();
      M.Modal.init($('.modal'));
      loadImages();

    });
</script>
<script nomodule>
  M.toast({html: 'current browser not support javascript module'});
</script>
</body>
</html>
